// hooks.ts
import { useEffect, useState } from 'react';
import { Context } from './context';
import type { TypedKey } from './types';

// 创建全局context实例
const globalContext = new Context();

// 使用useListen钩子
export function useListen<T>(key: TypedKey<T>): [T, (value: T) => void] {
  const [value, setValue] = useState<T>(() => globalContext.getData(key));

  useEffect(() => {
    const unsubscribe = globalContext.subscribe(key, (newValue: T) => {
      setValue(newValue);
    });
    return unsubscribe;
  }, [key]);

  const set = (newValue: T) => globalContext.setData(key, newValue);

  return [value, set];
}
